package com.william.jdbcplus.core.dialect.ddl.uk.impl;

import com.william.jdbcplus.common.entity.Entity;
import com.william.jdbcplus.core.dialect.ddl.uk.IUk;
import com.william.jdbcplus.core.meta.TableHelperUtil;
import com.william.jdbcplus.core.meta.TableInfo;
import com.william.jdbcplus.core.meta.TableUkInfo;
import com.william.jdbcplus.core.toolkit.StringPool;

import java.util.stream.Collectors;

/**
 * Oracle 唯一键实现
 *
 * @author william
 */
public class OracleUk implements IUk {
    @Override
    public <M extends Entity> String add(Class<M> clazz, TableUkInfo ukInfo) {
        TableInfo tableInfo = TableHelperUtil.getTableInfo(clazz);
        String columnNames = ukInfo.getColumns().stream().collect(Collectors.joining(StringPool.COMMA));
        String uniqueName = ukInfo.getShortUkName();
        StringBuffer sqlBuffer = new StringBuffer();
        sqlBuffer.append("alter table " + tableInfo.getTableName() + " add constraint  " + uniqueName + " unique (" + columnNames + ");");
        return sqlBuffer.toString();
    }

    @Override
    public <M extends Entity> String modify(Class<M> clazz, TableUkInfo ukInfo, TableUkInfo dbUk) {
        // alter index SYS_C00120182 rename to index_plat_123
        String dbUkName = dbUk.getUkName();
        String uniqueName = ukInfo.getShortUkName();
        StringBuffer sqlBuffer = new StringBuffer();
        sqlBuffer.append("alter index ")
                .append(dbUkName)
                .append(" rename to ")
                .append(uniqueName)
                .append(";");
        return sqlBuffer.toString();
    }

    @Override
    public <M extends Entity> String drop(Class<M> clazz, TableUkInfo dbUk) {
        TableInfo tableInfo = TableHelperUtil.getTableInfo(clazz);
        String uniqueName = dbUk.getUkName();
        StringBuffer sqlBuffer = new StringBuffer();
        sqlBuffer.append("alter table " + tableInfo.getTableName() + " drop constraint " + uniqueName + ";");
        return sqlBuffer.toString();
    }

    @Override
    public <M extends Entity> Boolean match(Class<M> clazz, TableUkInfo ukInfo, TableUkInfo dbUk) {
        if (!ukInfo.getShortUkName().equalsIgnoreCase(dbUk.getUkName())) {
            return false;
        }

        return true;
    }
}
